var DeviceForm = function () {
  var CodeValid = function () {
    var template = /* html */ `
      <div v-loading.fullscreen.lock="loading" style="padding:0 10px 5px">
        <div>
          <el-input size="small" v-model="codeValue" placeholder="请输入校验码">
          </el-input>
        </div>
        <div style="text-align:center;margin-top:10px">
          <el-button size="small" type="primary" @click="ensure">提交校验</el-button>
          <el-button :disabled="count!==0" size="small" type="primary" @click="sendCode">
            <span>重新发送校验码</span>
            <span v-if="count!==0">({{count}})</span>
          </el-button>
        </div>
      </div>
    `;

    return {
      data: function () {
        return {
          loading: false,
          count: 60,
          codeValue: '',
          interval: null
        };
      },

      created: function () {
        this.resetCount();
      },

      beforeDestroy:function(){
        this.clearInterval();
      },

      methods: {
        resetCount: function () {
          var self = this;
          var interval = setInterval(function () {
            var count = self.count;
            count--;
            if (count <= 0) {
              count = 0;
              self.clearInterval();
            }
            self.count = count;
          }, 1000);
          this.interval = interval;
        },

        sendCode: function () {
          this.loading = true;
          var self = this;
          ajaxRequest('dingTalk/getTokenForRuianCode').then(function () {
            self.loading = false;
            self.count = 60;
            self.resetCount();
          }).catch(function () {
            self.loading = false;
          });
        },

        ensure: function () {
          var codeValue = this.codeValue;
          if (codeValue.trim() === '') {
            this.$alert('请输入校验码', '信息');
            return;
          }

          this.loading = true;
          var self = this;
          return ajaxRequest('dingTalk/checkTokenForRuianCode', {
            token: codeValue
          }).then(function () {
            self.loading = false;
            self.$emit('valid-success');
          }).catch(function () {
            self.loading = false;
          });
        },

        clearInterval: function () {
          var interval = this.interval;
          if (interval !== null) {
            window.clearInterval(interval);
            this.interval = null;
          }
        }
      },

      template: template
    };
  }();

  var DeviceFormModel = function (device) {
    BaseModel.call(this);
    var self = this;

    var fn = {
      initData: function (device) {
        if (device === undefined) {
          device = {};
          self.temperatureBasic = undefined;
          self.isValid = false;
        } else {
          self.id = device.id;
          self.temperatureBasic = device.temperatureBasic;
          self.isValid = true;
        }

        var fields = ['deviceType', 'deviceId', 'deviceName', 'codeName', 'codeId', 'codeArea'];
        self.setDataFromObj(device, fields, '');
      }
    };

    this.checkValid = function () {
      var fields = ['deviceType', 'deviceId', 'deviceName'];
      var code = this.checkRequiredFields(fields, true);
      if (code !== '') {
        return code;
      }

      var codeName = this.codeName;
      var codeId = this.codeId;

      if (codeName === '' && codeId === '') {
        return '';
      }
      if (codeName === '') {
        return 'codeName';
      }
      if (codeId === '') {
        return 'codeId';
      }
      if (!this.isValid) {
        return 'codeArea';
      }
      return '';
    };

    this.getObject = function () {
      var postData = {};
      var id = this.id;
      if (!SysUtil.isEmpty(id)) {
        postData.id = id;
      }
      var fields = ['deviceType', 'deviceId', 'deviceName', 'temperatureBasic', 'deviceName', 'codeName', 'codeId', 'codeArea'];
      this.setPostData(postData, fields);
      return postData;
    };

    fn.initData(device);
  };

  var template = /* html */ `
    <div class="device-form" v-loading.fullscreen.lock="loading">
      <el-form label-width="auto" size="medium">
        <el-form-item label="设备类型">
          <el-select v-if="type==='add'" v-model="deviceForm.deviceType" class="form-input" placeholder="请选择设备类型">
            <el-option v-for="item in deviceTypeList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
          <span v-else>{{i18n.getMsg('attendance.device.type.'+deviceForm.deviceType)}}</span>
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-if="type==='add'" v-model="deviceForm.deviceId" class="form-input" placeholder="请输入设备编号">
          </el-input>
          <span v-else>{{deviceForm.deviceId}}</span>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input show-word-limit v-model="deviceForm.deviceName" class="form-input" maxlength="20" placeholder="不超过20个字符">
          </el-input>
        </el-form-item>
        <el-form-item label="标准体温">
          <el-input-number is-decimal-zero v-model="deviceForm.temperatureBasic" class="form-input" :controls="false" :min="35" :max="37.5" :precision="1"
            placeholder="请输入标准体温">
          </el-input-number>
        </el-form-item>
        <el-form-item label="地方码">
          <el-select filterable v-model="deviceForm.codeName" class="form-input" placeholder="请选择地方码" @change="setCodeArea" :disabled="!codeCanUpdate">
            <el-option v-for="item in codeNameList" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡口号">
          <el-input v-model="deviceForm.codeId" class="form-input" placeholder="请输入由数字组成的卡口号" @change="codeIdChange" :disabled="!codeCanUpdate">
          </el-input>
        </el-form-item>
        <el-form-item label="卡口位置">
          <span>{{deviceForm.codeArea}}</span>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="ensure">
          <span v-if="type==='add'">新增</span>
          <span v-else>修改</span>
        </el-button>
        <el-button v-if="!codeCanUpdate" size="medium" type="primary" @click="applyUpdate">
          <span v-if="type==='add'">申请添加地方码</span>
          <span v-else>申请修改地方码</span>
        </el-button>
      </div>

      <el-dialog append-to-body title="校验码" :visible.sync="openApply" width="270px" top="calc(50vh - 80px)"
        :close-on-click-modal="false">
        <div style="height:100px;overflow:auto">
          <code-valid v-if="openApply" @valid-success="validSuccess"></code-valid>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    props: {
      device: {
        type: Object,
        default: function () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      }
    },

    data: function () {
      var deviceForm;
      if (this.type === 'add') {
        deviceForm = new DeviceFormModel();
      } else {
        deviceForm = new DeviceFormModel(this.device);
      }
      return {
        loading: false,
        deviceForm: deviceForm,
        deviceTypeList: i18n.getDropDown('attendance.device.type', [1, 2, 3]),
        codeNameList: ['瑞安码'],
        codeCanUpdate: false,
        openApply: false
      };
    },

    methods: {
      setCodeArea: function () {
        var deviceForm = this.deviceForm;
        this.loading = true;
        var self = this;
        this.getCodeArea().then(function (codeArea) {
          if (codeArea === null) {
            self.$alert('获取不到卡口位置，请检查卡口号是否输入正确', '信息');
            codeArea = '';
          }
          deviceForm.codeArea = codeArea;
          deviceForm.isValid = codeArea !== '';
          self.loading = false;
        });
      },

      getCodeArea: function () {
        var deviceForm = this.deviceForm;
        var codeId = deviceForm.codeId;
        var codeName = deviceForm.codeName;
        if (codeId === '' || codeName === '') {
          return Promise.resolve('');
        }

        return ajaxRequest('dingTalk/getCodeAreaByCodeId', {
          codeName: codeName,
          codeId: codeId
        }).then(function (data) {
          var codeArea = data.data;
          if (codeArea === '') {
            return null;
          }
          return codeArea;
        }).catch(function () {
          return '';
        });
      },

      codeIdChange: function () {
        var deviceForm = this.deviceForm;
        var codeId = deviceForm.codeId;
        if (codeId.trim() === '') {
          deviceForm.codeArea = '';
          deviceForm.isValid = false;
          return;
        }

        if (!/^[0-9]+$/.test(codeId)) {
          this.$alert('卡口号只能由数字组成', '信息');
          return;
        }
        this.setCodeArea();
      },

      ensure: function () {
        var deviceForm = this.deviceForm;
        var code = deviceForm.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`attendance.device.error.${code}`);
          this.$alert(msg, '信息');
          return;
        }

        if (this.type === 'add') {
          this.addDevice(deviceForm);
        } else {
          this.updateDevice(deviceForm);
        }
      },

      addDevice: function (deviceForm) {
        var postData = deviceForm.getObject();
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/insertAttendDevice', postData).then(function () {
          self.loading = false;
          self.$alert('设备新增成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      updateDevice: function (deviceForm) {
        var postData = deviceForm.getObject();
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/updateAttendDevice', postData).then(function () {
          self.loading = false;
          self.$alert('设备修改成功', '信息', {
            callback: function () {
              self.$emit('save-success');
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      applyUpdate: function () {
        this.loading = true;
        var self = this;
        ajaxRequest('dingTalk/getTokenForRuianCode').then(function () {
          self.loading = false;
          self.openApply = true;
        }).catch(function () {
          self.loading = false;
        });
      },

      validSuccess: function () {
        this.openApply = false;
        this.codeCanUpdate = true;
      }
    },

    components: {
      CodeValid: CodeValid
    },

    template: template
  };
}();
